package com.yzh.openai.types.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.yzh.openai.types.common.Constants;
import com.yzh.openai.types.exception.BusinessException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel工具类
 * 基于EasyExcel实现
 */
public class ExcelUtils {
    /**
     * Excel数据提取为Csv格式
     *
     * @param multipartFile
     * @return
     */
    public static String excelToCsv(MultipartFile multipartFile) {
        List<Map<Integer, String>> listMap = null;
        try {
            listMap = EasyExcel.read(multipartFile.getInputStream())
                    .sheet()
                    .headRowNumber(0)
                    .doReadSync();
        } catch (Exception e) {
            throw new BusinessException(Constants.ResponseCode.UN_ERROR, "Excel文件读取出错");
        }
        // 转为CSV
        StringBuilder csv = new StringBuilder();
        // 获取每行元素
        for (int i = 0; i < listMap.size(); i++) {
            Map<Integer, String> contentMap = listMap.get(i);
            List<String> content = contentMap.values().stream().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
            csv.append(StringUtils.join(content, ",")).append("\n");
        }
        return csv.toString();
    }

    public static void main(String[] args) throws IOException {
        excelToCsv(null);
    }
}
